

#include "stdint.h"

#include <platform.h>

#include "build/debug.h"
#include "drivers/io.h"

#include "drivers/time.h"

//01111110
//habcdefg
// a
//f b
// g 
//e c
// d h
uint8_t convTable[] = {
  //  0     1     2     3     4     5     6     7     8     9     A     B     C     D     E     F    -     
//~0xC0,~0xF9,~0xA4,~0xB0,~0x99,~0x92,~0x82,~0xF8,~0x80,~0x90,~0x88,~0x83,~0xC6,~0xA1,~0x86,~0x8E    16    17
   0x7E, 0x30, 0x6D, 0x79, 0x33, 0x5B, 0x5F, 0x70, 0x7F, 0x7B, 0x77, 0x1F, 0x4E, 0x3D, 0x4F, 0x47, 0x01, 0x00
};

#define Max7219_pinCLKH clkGpio->BSRR = clkPin
#define Max7219_pinCLKL clkGpio->BRR = clkPin
#define Max7219_pinCSH  csGpio->BSRR = csPin
#define Max7219_pinCSL  csGpio->BRR = csPin
#define Max7219_pinDINH dinGpio->BSRR = dinPin
#define Max7219_pinDINL dinGpio->BRR = dinPin

static uint16_t clkPin;
static uint16_t csPin;
static uint16_t dinPin;
GPIO_TypeDef* clkGpio;
GPIO_TypeDef* csGpio;
GPIO_TypeDef* dinGpio;


void Write_Max7219_byte(uint8_t DATA)
{
  uint8_t i;
  for(i=8;i>=1;i--)
  {
    Max7219_pinCLKL;
    if(DATA&0x80){
      Max7219_pinDINH;
    }else{
      Max7219_pinDINL;
    }
    DATA=DATA<<1;
    Max7219_pinCLKH;
  }
}
void Write_Max7219(uint8_t address, uint8_t dat)
{
  Max7219_pinCSL;
  Write_Max7219_byte(address); // 写入地址，即数码管编号
  Write_Max7219_byte(dat);     // 写入数据，即数码管显示数字
  Max7219_pinCSH;
}
void Write_Char_Max7219(uint8_t address, uint8_t chr)
{
  Write_Max7219(address, convTable[chr]);
}

void Init_MAX7219(){
    IO_t clk = IOGetByTag(IO_TAG(MAX7219_CLK));
    IO_t cs = IOGetByTag(IO_TAG(MAX7219_CS));
    IO_t din = IOGetByTag(IO_TAG(MAX7219_DIN));

    clkPin = IO_Pin(clk);
    csPin = IO_Pin(cs);
    dinPin = IO_Pin(din);

    clkGpio = IO_GPIO(clk);
    csGpio = IO_GPIO(cs);
    dinGpio = IO_GPIO(din);

    IOConfigGPIO(clk, IO_CONFIG(GPIO_Mode_Out_PP,      GPIO_Speed_50MHz));
    IOConfigGPIO(cs, IO_CONFIG(GPIO_Mode_Out_PP,      GPIO_Speed_50MHz));
    IOConfigGPIO(din, IO_CONFIG(GPIO_Mode_Out_PP,      GPIO_Speed_50MHz));

    Write_Max7219(0x09, 0x00);       //译码方式：BCD码
    Write_Max7219(0x0a, 0x03);       //亮度 
    Write_Max7219(0x0b, 0x07);       //扫描界限；8个数码管显示
    Write_Max7219(0x0c, 0x01);       //掉电模式：0，普通模式：1
    Write_Max7219(0x0f, 0x00);       //显示测试：1；测试结束，正常显示：0

    Write_Char_Max7219(1,0x8);
    Write_Char_Max7219(2,0x7);
    Write_Char_Max7219(3,0x6);
    Write_Char_Max7219(4,0x5);
    Write_Char_Max7219(5,0x4);
    Write_Char_Max7219(6,0x3);
    Write_Char_Max7219(7,0x2);
    Write_Char_Max7219(8,0x1);
}
